﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Hr;

namespace ESOL.WinUI.Sales
{
    public partial class frmMaintainDeliveryOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region vars
        public SalesDeliveryOrderEntity SelectedDeliveryOrder { get; set; }
        private List<SalesDeliveryItemEntity> DeleteList = new List<SalesDeliveryItemEntity>();
        private List<SalesProdPlanApplicationItemEntity> mListApplicationItem;
        #endregion

        #region ctors
        public frmMaintainDeliveryOrder()
        {
            InitializeComponent();
            if (SelectedDeliveryOrder == null)
            {
                SelectedDeliveryOrder = new SalesDeliveryOrderEntity();
                SelectedDeliveryOrder.DeliveryOrderId = Guid.NewGuid().ToString();
            }
        }
        public frmMaintainDeliveryOrder(List<SalesProdPlanApplicationItemEntity> list, MstCustomerEntity customer)
        {
            InitializeComponent();
            if (SelectedDeliveryOrder == null)
            {
                SelectedDeliveryOrder = new SalesDeliveryOrderEntity();
                SelectedDeliveryOrder.DeliveryOrderId = Guid.NewGuid().ToString();
            }

            mListApplicationItem = list;
            txtCustomer.Tag = customer;
        }
        #endregion

        #region functions
        private void SetFieldsByCustomer(MstCustomerEntity customer)
        {
            if (customer != null)
            {
                txtCustomer.Tag = customer;
                txtCustomer.Text = customer.CustomerName;
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, customer.CustomerId, false);
                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, customer.CustomerId, true);
            }
            else
            {
                txtCustomer.Tag = null;
                txtCustomer.Text = "";
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, "", false);
                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, "", true);
            }
            //Set default fields by customer
            if (customer != null)
            {
                txtDeliveryPlace.Text = customer.ReceivedAddress;
                if (cmbCustomerContact.SelectedItem != null)
                {
                    MstCustomerContactEntity contact = (MstCustomerContactEntity)cmbCustomerContact.SelectedItem;
                    if (contact != null)
                    {
                        txtReceivedPerson.Text = contact.ContactName;
                        txtReceivedPhone.Text = contact.ContactMobilephone;
                    }
                }
            }
        }
        private void SetDataRowByApplicationItem(DataRow dr, SalesProdPlanApplicationItemEntity entity)
        {
            dr["CONTACT_ID"] = entity.ContactId;
            dr["DELIVERY_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["DELIVERY_ORDER_ID"] = SelectedDeliveryOrder.DeliveryOrderId;
            dr["APPLICATION_ITEM_ID"] = entity.ApplicationItemId;
            dr["PRICE"] = decimal.Round(entity.Price,2);
            dr["QTY"] = entity.Qty;
            dr["TOTAL_AMOUNT"] = decimal.Round(entity.Price * entity.Qty,2);
            dr["DELIVERY_APPLICATION"] = entity.DeliveryApplication;
            dr["PACKAGE_TYPE"] = entity.PackageType;
            dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;

            MstProductEntity product = MstProductBs.GetMstProductByApplicationItemID(entity.ApplicationItemId);
            if (product != null)
            {
                dr["PRODUCT_ID"] = product.ProductId;
                dr["PRODUCT_CODE"] = product.ProductCode;
                dr["PRODUCT_SPEC_IN"] = product.ProductSpecIn;
                dr["MATERIAL"] = product.Material;
                dr["UNIT"] = product.Unit;
            }
        }
        private void SetGridViewByApplicationItems()
        {
            if (mListApplicationItem == null)
            {
                return;
            }
            gvMain.DataSource = SalesDeliveryItemBs.GetDataSetByDeliveryID("").Tables[0];
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (SalesProdPlanApplicationItemEntity entity in mListApplicationItem)
            {
                DataRow dr = dt.NewRow();
                SetDataRowByApplicationItem(dr, entity);
                dt.Rows.Add(dr);
            }
        }
        private void BindComboBox()
        {
            //List<MstWarehouseEntity> list = MstWarehouseBs.GetMstWarehouseAllList();
            //MstWarehouseEntity entity = new MstWarehouseEntity();
            //list.Insert(0, entity);
            //cmbWarehouseCode.DataSource = list;
            //cmbWarehouseCode.DisplayMember = "WarehouseName";
            //cmbWarehouseCode.ValueMember = "WarehouseCode";

            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "DO", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbDeliveryType, "DW", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbTrasportType, "TF", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPACKAGE_TYPE, "PT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colDELIVERY_APPLICATION, "DA", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }
        private void BindDataGridDetail()
        {
            if (SelectedDeliveryOrder == null)
            {
                gvMain.DataSource = null;
                return;
            }
            DataSet ds = SalesDeliveryItemBs.GetDataSetByDeliveryID(SelectedDeliveryOrder.DeliveryOrderId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<SalesDeliveryItemEntity>();
        }
        private void SetFields()
        {
            if (SelectedDeliveryOrder == null)
            {
                BindDataGridDetail();
                return;
            }
            if (string.IsNullOrEmpty(SelectedDeliveryOrder.CustomerId) == false)
            {
                MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedDeliveryOrder.CustomerId);
                SetFieldsByCustomer(customer);
            }
            txtDeliveryOrderCode.Text = SelectedDeliveryOrder.DeliveryOrderCode;
            if (string.IsNullOrEmpty(txtDeliveryOrderCode.Text))
            {
                txtDeliveryOrderCode.Text = "自动生成";
            }
            dtpDeliveryDate.EditValue = SelectedDeliveryOrder.DeliveryDate;
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtDeliveryPerson.Tag = person;
                    txtDeliveryPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedDeliveryOrder.DeliveryPerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedDeliveryOrder.DeliveryPerson);
                    if (person != null)
                    {
                        txtDeliveryPerson.Tag = person;
                        txtDeliveryPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            cmbTrasportType.SetSelectedValue(SelectedDeliveryOrder.TransportType);
            cmbDeliveryType.SetSelectedValue(SelectedDeliveryOrder.DeliveryType);
            cmbStatus.SetSelectedValue(SelectedDeliveryOrder.Status);
            txtRemark.Text = SelectedDeliveryOrder.Remark;

            txtDeliveryPlace.Text = SelectedDeliveryOrder.DeliveryPlace;
            txtReceivedPerson.Text = SelectedDeliveryOrder.ReceivedPerson;
            txtReceivedPhone.Text = SelectedDeliveryOrder.ReceivedPersonPhone;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedDeliveryOrder.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedDeliveryOrder.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedDeliveryOrder.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedDeliveryOrder.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedDeliveryOrder.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedDeliveryOrder.ApprovedBy);

            BindDataGridDetail();
        }
        private void SetEntity()
        {
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SelectedDeliveryOrder.CustomerId = ((MstCustomerEntity)txtCustomer.Tag).CustomerId;
            }
            if (dtpDeliveryDate.EditValue!=null)
            {
                SelectedDeliveryOrder.DeliveryDate = Convert.ToDateTime(dtpDeliveryDate.EditValue); 
            }
            if (txtDeliveryPerson.Tag != null && txtDeliveryPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedDeliveryOrder.DeliveryPerson = ((MstPersonEntity)txtDeliveryPerson.Tag).PersonId;
            }
            //if (cmbWarehouseCode.SelectedValue != null && cmbWarehouseCode.SelectedValue.ToString().Trim() != "")
            //{
            //    SelectedDeliveryOrder.WarehouseCode = cmbWarehouseCode.SelectedValue.ToString().Trim();
            //}
            if (cmbTrasportType.SelectedValue != null && cmbTrasportType.SelectedValue.ToString().Trim() != "")
            {
                SelectedDeliveryOrder.TransportType = cmbTrasportType.SelectedValue.ToString().Trim();
            }
            if (cmbDeliveryType.SelectedValue != null && cmbDeliveryType.SelectedValue.ToString().Trim() != "")
            {
                SelectedDeliveryOrder.DeliveryType = cmbDeliveryType.SelectedValue.ToString().Trim();
            }
            SelectedDeliveryOrder.Status = DeliveryOrderStatus.DO02.ToString();
            SelectedDeliveryOrder.Remark = txtRemark.Text;

            SelectedDeliveryOrder.DeliveryPlace = txtDeliveryPlace.Text;
            SelectedDeliveryOrder.ReceivedPerson = txtReceivedPerson.Text;
            SelectedDeliveryOrder.ReceivedPersonPhone = txtReceivedPhone.Text;
            if (cmbDeliveryType.SelectedValue != null && cmbDeliveryType.SelectedValue.ToString().Trim() != "")
            {
                SelectedDeliveryOrder.DeliveryType = cmbDeliveryType.SelectedValue.ToString();
            }

            if (ThisActionType == ActionType.New)
            {
                SelectedDeliveryOrder.CreatedDate = DateTime.Now;
                SelectedDeliveryOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedDeliveryOrder.LastModifiedDate = DateTime.Now;
                SelectedDeliveryOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbDeliveryType.Text))
            {
                MessageBox.Show("送货方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtDeliveryPerson.Text))
            {
                MessageBox.Show("申请人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtReceivedPerson.Text))
            {
                MessageBox.Show("收货人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtDeliveryPlace.Text))
            {
                MessageBox.Show("交货地点不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpDeliveryDate.EditValue == null)
            {
                MessageBox.Show("申请日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }            
            if (gvMain.DataSource == null)
            {
                MessageBox.Show("发货申请单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (UICommonFunctions.CheckDataGrid(gvMain)==false)
            {
                return false;
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = SalesDeliveryOrderBs.SaveDeliveryOrder(true, SelectedDeliveryOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = SalesDeliveryOrderBs.SaveDeliveryOrder(false, SelectedDeliveryOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedDeliveryOrder.ApprovedDate = DateTime.Now;
                    SelectedDeliveryOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = SalesDeliveryOrderBs.UpdateSalesDeliveryOrder(SelectedDeliveryOrder);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region events
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SetFieldsByCustomer((MstCustomerEntity)txtCustomer.Tag);
            }
            SetGridViewByApplicationItems();
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedDeliveryOrder = new SalesDeliveryOrderEntity();
                SelectedDeliveryOrder.DeliveryOrderId = Guid.NewGuid().ToString();
                SetFields();
            }
        }
        protected override void Click_Approve()
        {
            if (SelectedDeliveryOrder == null)
            {
                return;
            }
            SelectedDeliveryOrder.Status = DeliveryOrderStatus.DO03.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (SelectedDeliveryOrder == null)
            {
                return;
            }
            SelectedDeliveryOrder.Status = DeliveryOrderStatus.DO04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        private void txtDeliveryPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtDeliveryPerson.Text = frm.SelectedPerson.NameCn;
                txtDeliveryPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtDeliveryPerson.Text = "";
                txtDeliveryPerson.Tag = null;
            }
        }
        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtDeliveryPerson.Tag == null || txtDeliveryPerson.Tag.GetType() != typeof(MstPersonEntity))
            {
                MessageBox.Show("请先选择业务员！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery((MstPersonEntity)txtDeliveryPerson.Tag);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                SetFieldsByCustomer(frm.SelectedCustomer);
            }
            else
            {
                SetFieldsByCustomer(null);
            }
        }
        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;

            frmMaintainProductPlanApplicationItemQuery frm = new frmMaintainProductPlanApplicationItemQuery(false);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedApplicationItemList != null && frm.SelectedApplicationItemList.Count != 0)
            {
                foreach (SalesProdPlanApplicationItemEntity entity in frm.SelectedApplicationItemList)
                {
                    DataRow dr = dt.NewRow();
                    SetDataRowByApplicationItem(dr, entity);
                    dt.Rows.Add(dr);
                }
            }
        }
        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (drSelected==null)
            {
                return;
            }
            if (drSelected.RowState != DataRowState.Added)
            {
                SalesDeliveryItemEntity entity = new SalesDeliveryItemEntity(drSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvMain.DataSource as DataTable;
            dt.Rows.Remove(drSelected);
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("QTY") || e.Column.FieldName.Equals("PRICE"))
            {
                decimal qty = CommonFunctions.ToDecimal(drSelected["QTY"]);
                decimal price = CommonFunctions.ToDecimal(drSelected["PRICE"]);
                drSelected["TOTAL_AMOUNT"] = qty * price;
            }
        }

        private void cmbCustomerContact_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCustomerContact.SelectedItem != null)
            {
                MstCustomerContactEntity entity = (MstCustomerContactEntity)cmbCustomerContact.SelectedItem;
                if (entity != null)
                {
                    txtReceivedPerson.Text = entity.ContactName;
                    txtReceivedPhone.Text = entity.ContactMobilephone;
                }
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductPlanApplicationItemQuery frm = new frmMaintainProductPlanApplicationItemQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedApplicationItemList != null && frm.SelectedApplicationItemList.Count != 0)
            {
                foreach (SalesProdPlanApplicationItemEntity entity in frm.SelectedApplicationItemList)
                {
                    SetDataRowByApplicationItem(drSelected, entity);
                    break;
                }
            }
        }

        DataRow drSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            drSelected = gridView1.GetFocusedDataRow();
        }
        #endregion


    }
}
